/*
 *所有关于products类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*productsService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VolPro.Core.BaseProvider;
using VolPro.Core.Extensions.AutofacManager;
using VolPro.Entity.DomainModels;
using System.Linq;
using VolPro.Core.Utilities;
using System.Linq.Expressions;
using VolPro.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using SMes.DbMethod.IRepositories;
using System.Net;
using VolPro.Core.ManageUser;

namespace SMes.DbMethod.Services
{
    public partial class productsService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IproductsRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public productsService(
            IproductsRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            WebResponseContent webResponse = new WebResponseContent();
            AddOnExecute = (SaveModel saveDataModel) =>
            {
                saveDataModel.MainData.TryAdd("CreatedDate", DateTime.Now);
                saveDataModel.MainData.TryAdd("UpdateDate", DateTime.Now);
                saveDataModel.MainData.TryAdd("CreateUser", UserContext.Current.UserTrueName);
                //如果返回false,后面代码不会再执行
                return webResponse.OK();
            };
            return base.Add(saveDataModel);
        }
        public override WebResponseContent Update(SaveModel saveModel)
        {
            WebResponseContent webResponse = new WebResponseContent();
            UpdateOnExecute = (SaveModel saveModel) =>
            {
                saveModel.MainData.TryAdd("UpdateDate", DateTime.Now);
                return webResponse.OK();
            };
            return base.Update(saveModel);
        }
        public override WebResponseContent Import(List<IFormFile> files)
        {
            WebResponseContent webResponse = new WebResponseContent();
            ImportOnExecuting = (List<products> list) =>
            {
                var repdata = list.GroupBy(x => x.ProductCode).Where(m => m.Count() > 1).Select(m => m.Key).ToList();
                if (repdata != null && repdata.Count > 0)
                {
                    return webResponse.Error($"Excel中存在[物料编码]重复的数据,重复的[物料编码(ProductCode)]:{string.Join(";", repdata)}");
                }
                foreach (var item in list)
                {
                    item.CreatedDate = DateTime.Now;
                    item.UpdateDate = DateTime.Now;
                    item.CreateUser = UserContext.Current.UserTrueName;
                }
                
                var productCodes = list.Select(x => x.ProductCode).ToList();
                var existProductsIDsCodes = _repository.FindAsIQueryable(x => productCodes.Contains(x.ProductCode)).Select(x => new
                {
                    x.ID,
                    x.ProductCode
                }).ToList();
                var existProductCodes = existProductsIDsCodes.Select(x => x.ProductCode).ToList();
                var toAdd = list.Where(x => !existProductCodes.Contains(x.ProductCode)).ToList();
                var toUpdate = list.Join(existProductsIDsCodes, u => u.ProductCode, t => t.ProductCode,
                    (u, t) => new products
                    {
                        ID = t.ID,
                        ProductCode = t.ProductCode,
                        ProductName = u.ProductName,
                        DrawNo = u.DrawNo,
                        Unit = u.Unit,
                        IsMaterial = u.IsMaterial,
                        Memo = u.Memo,
                        CreatedDate = u.CreatedDate,
                        UpdateDate = u.UpdateDate,
                        CreateUser = u.CreateUser
                    }).ToList();
                string message = null;
                if (toUpdate != null && toUpdate.Count > 0)
                {
                    var productCodesRe = toUpdate.Select(x => x.ProductCode).ToList();
                    message = $"数据库与Excel有重复[物料编码]，重复[物料编码]已做更新处理。重复的[物料编码(ProductCode)]:{string.Join(";", productCodesRe)}";
                }
                var tuple = new Tuple<List<products>, List<products>>(toAdd, toUpdate);
                return webResponse.OK(message, tuple);
            };
            return base.ImportAdvance(files);
            //return base.Import(files);
        }
    }
}
